<template>
  <div class="login_page">
    <div class="form-box">
      <h2>叩丁狼电商管理系统</h2>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input
            type="password"
            v-model="ruleForm.pwd"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%" type="primary" @click="loginFn"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { LoginApi } from "../../request/api";
export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" },
          { validator: this.loginVal, trigger: "blur" }
        ],
        pwd: [{ required: true, message: "密码不能为空", trigger: "blur" }]
      }
    };
  },
  methods: {
    loginVal(rule, value, cb) {
      if (value.length > 1 && value.length < 20) {
        cb();
      } else {
        cb("账号长度为1到20个字符");
      }
    },
    loginFn() {
      this.$refs.ruleForm.validate(val => {
        if (val) {
          console.log("校验通过");
          LoginApi({
            username: this.ruleForm.username,
            password: this.ruleForm.pwd
          }).then(res => {
            if (res.errno === 0) {
              localStorage.setItem("token", res.data.token);
              this.$router.push("/home")
            }
          });
        } else {
          console.log("校验不通过");
        }
      });
    }
  }
};
</script>
 
<style lang = "less" scoped>
.login_page {
  height: 100%;
  background-color: #324057;
  text-align: center;
  position: relative;
  .form-box {
    width: 330px;
    height: 300px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    h2 {
      margin-bottom: 20px;
      color: #fff;
    }
  }
}
</style>